<?php

require_once dirname(__FILE__) . '/../lib/ct_documentoGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/ct_documentoGeneratorHelper.class.php';

/**
 * ct_documento actions.
 *
 * @package    ingenyo-biblio
 * @subpackage ct_documento
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class ct_documentoActions extends autoCt_documentoActions
{

  public function executePrestarLibro(sfWebRequest $request)
  {
    $id_documento = $request->getParameter('id');
    $this->getUser()->setAttribute('documento', $id_documento);
    $this->redirect('bb_prestamo/new');

  }

  public function executeReservarLibro(sfWebRequest $request)
  {
    $id_documento = $request->getParameter('id');
    $this->getUser()->setAttribute('documento', $id_documento);
    $this->redirect('bb_reserva_libro/new');

  }

  public function executeVerPrestamos(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->getUser()->setAttribute('documento', $documento);
    $this->redirect('bb_prestamo');

  }

  public function executeVerReservas(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->getUser()->setAttribute('id_documento', $documento->getId());
    $this->redirect('bb_reserva_libro/indexByDocumento');

  }

  public function executeVerComentarios(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->getUser()->setAttribute('id_documento', $documento->getId());
    $this->redirect('ct_documento_comentario');

  }

  public function executeIndex(sfWebRequest $request)
  {

    $this->getUser()->clearAllAttribute('idDocumento');

    parent::executeIndex($request);
    $this->filters = new CtDocumentoFormFilterCollection();

  }

  public function executeBuscar(sfWebRequest $request)
  {
    $form = new CtDocumentoFormFilterCollection();
    $form->bind($request->getParameter('filters'));
    $pager = new sfPropelPager('CTDocumento', sfConfig::get('app_max_documentos_en_busqueda'));
    $pager->setCriteria($form->getCriteriaFilter());
    $pager->setPage($request->getParameter('page', 1));

    $pager->init();

    $this->sort = $this->getSort();
    $this->helper = new ct_documentoGeneratorHelper();
    sfConfig::set('sf_web_debug', false);
    sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');

    return $this->renderText(get_partial('result_list', array('pager' => $pager,
          'sort' => $this->sort,
          'configuration' => $this->configuration,
          'helper' => $this->helper)));

  }

  public function executeAddCustom(sfWebRequest $request)
  {
    $next = $request->getParameter('next');
    $is_the_last = $request->getParameter('is_the_last');
    $form = new CtDocumentoFormFilterCollection();
    $form->addCustom($next, $is_the_last);
    sfConfig::set('sf_web_debug', false);
    sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
    return $this->renderText(get_partial('custom', array('custom_filters' => $form['filters']['custom'][$next],
          'add' => true)));

  }

  public function executeAddRepetible(sfWebRequest $request)
  {
    $padre = $request->getParameter('padre');
    $id_caracteristica = $request->getParameter('id_caracteristica');
    // Preguntar si ya existe el documetno para formulario de edicion TODO

    $form = new CtdocumentoForm(array(), array('new_for_add_repetible' => true));
    $form->addRepetible($id_caracteristica, $request->getParameter('padre'), $request->getParameter('iteracion'), $request->getParameter('next_repetible'));

    return $this->renderPartial('addRepetible', array('form' => $form));

  }

  public function executeNuevoMonografico(sfWebRequest $request)
  {
    $this->getUser()->clearAttribute('idDocumento');
    $this->CtDocumento = new CtDocumento();
    $this->form = new CtdocumentoMonograficoForm($this->CtDocumento);
    $this->setTemplate('newMonografico');
    $this->setLayout('layout_iframe');

  }

  public function procesarForm($templateNew, sfWebRequest $request, $type)
  {
    if ($this->form->isValid())
    {
      $this->form->save();
      $this->getUser()->setAttribute('idDocumento', $this->form->getObject()->getId());
      if ($this->form->isNew())
      {
        $this->getUser()->setFlash('notice', 'El documento fue creado con exito', false);
      }
      else
      {
        $this->getUser()->setFlash('notice', 'El documento fue actualizado con exito', false);
      }

      $this->CtDocumento = $this->form->getObject();
      switch ($type)
      {
        case 'Monografico':
          $this->form = new CtdocumentoMonograficoForm($this->CtDocumento);
          $this->setTemplate('editMonografico');
          break;
        case 'Analitico':
          $this->form = new CtdocumentoAnaliticoForm($this->CtDocumento);
          $this->setTemplate('editAnalitico');
          break;
        case 'Periodico':
          $this->form = new CtdocumentoPeriodicoForm($this->CtDocumento);
          $this->setTemplate('editPeriodico');
          break;
      }
    }
    else
    {
      if ($this->form->isNew())
      {
        $this->getUser()->setFlash('error', 'El documento no fue creado debido a que falta completar algunos campos requeridos', false);
        $this->setTemplate($templateNew . $type);
      }
      else
      {
        $this->getUser()->setFlash('error', 'El documento no fue actualizado debido a que falta completar algunso campos requeridos', false);
        switch ($type)
        {
          case 'Monografico':
            $this->setTemplate('editMonografico');
            break;
          case 'Analitico':
            $this->setTemplate('editAnalitico');
            break;
          case 'Periodico':
            $this->setTemplate('editPeriodico');
            break;
        }
      }
    }
    $this->setLayout('layout_iframe');

  }

  public function executeSavePeriodico(sfWebRequest $request)
  {
    if ($this->getUser()->hasAttribute('idDocumento'))
    {
      $this->CtDocumento = CtDocumentoPeer::retrieveByPK($this->getUser()->getAttribute('idDocumento'));
    }
    else
    {
      $this->CtDocumento = new CtDocumento();
    }

    $this->form = new CtdocumentoPeriodicoForm($this->CtDocumento);
    $this->form->bind($request->getParameter($this->form->getName()));

    $this->procesarForm('newPeriodico', $request, 'Periodico');

  }

  public function executeSaveAnalitico(sfWebRequest $request)
  {
    if ($this->getUser()->hasAttribute('idDocumento'))
    {
      $this->CtDocumento = CtDocumentoPeer::retrieveByPK($this->getUser()->getAttribute('idDocumento'));
    }
    else
    {
      $this->CtDocumento = new CtDocumento();
    }
    $this->form = new CtdocumentoAnaliticoForm($this->CtDocumento);
    $this->form->bind($request->getParameter($this->form->getName()));

    $this->procesarForm('new', $request, 'Analitico');

  }

  public function executeSaveMonografico(sfWebRequest $request)
  {
    set_time_limit(0);

    if ($this->getUser()->hasAttribute('idDocumento'))
    {
      $this->CtDocumento = CtDocumentoPeer::retrieveByPK($this->getUser()->getAttribute('idDocumento'));
    }
    else
    {
      $this->CtDocumento = new CtDocumento();
    }

    $this->form = new CtdocumentoMonograficoForm($this->CtDocumento);
    $this->form->bind($request->getParameter($this->form->getName()));

    $this->procesarForm('new', $request, 'Monografico');

  }

  public function executeEdit(sfWebRequest $request)
  {
    set_time_limit(0);
    $this->CtDocumento = $this->getRoute()->getObject();

    $this->getUser()->setAttribute('idDocumento', $this->CtDocumento->getId());
    if ($this->CtDocumento->getTipoLibro() == sfConfig::get('app_monografico'))
    {
      $this->form = new CtdocumentoMonograficoForm($this->CtDocumento);
      $this->setTemplate('editMonografico');
    }
    else
    {##Agrgar analitico TODO
      $this->form = new CtdocumentoAnaliticoForm($this->CtDocumento);
      $this->setTemplate('editAnalitico');
    }
    $this->setLayout('layout_iframe');

  }

  public function executeVerFicha(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->caracteristicas = $documento->getCaracteristicasFicha();
    $this->caracteristicasAACR2 = $documento->getCaracteristicasFichaAACR2();
    if ($documento->getTipoLibro() == 'm')
    {
      $this->contenido = $documento->getContenido();
    }
    $this->tipo = 'Ficha';
    $this->setTemplate('show');
    $this->setLayout('layout_iframe');

  }

  public function executeVerDetalle(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->caracteristicas = $documento->getCaracteristicasDetalle();
    $this->caracteristicasAACR2 = $documento->getCaracteristicasDetalleAACR2();
    if ($documento->getTipoLibro() == 'm')
    {
      $this->contenido = $documento->getContenido();
    }
    $this->tipo = 'Detalle';
    $this->setTemplate('show');
    $this->setLayout('layout_iframe');

  }

  public function executeAgregarAnalitico(sfWebRequest $request)
  {
    $this->getUser()->clearAttribute('idDocumento');
    $this->getUser()->setAttribute('id_documento_monografico', $this->getRoute()->getObject()->getId());
    $this->CtDocumento = new CtDocumento();
    $this->form = new CtdocumentoAnaliticoForm($this->CtDocumento);

    $this->setTemplate('newAnalitico');
    $this->setLayout('layout_iframe');

  }

  public function executeNuevoPeriodico(sfWebRequest $request)
  {
    $this->getUser()->clearAttribute('idDocumento');
    $this->CtDocumento = new CtDocumento();
    $this->form = new CtdocumentoPeriodicoForm($this->CtDocumento);

    $this->setTemplate('newPeriodico');
    $this->setLayout('layout_iframe');

  }

  public function executeAgregarEjemplar(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->getUser()->setAttribute('documento', $documento);
    $this->redirect('ct_libro/new');

  }

  public function executeVerEjemplares(sfWebRequest $request)
  {
    $documento = $this->getRoute()->getObject();
    $this->getUser()->setAttribute('documento', $documento);
    $this->redirect('ct_libro');

  }

  public function executeDelete(sfWebRequest $request)
  {
    $this->request = $request;
    $this->CtDocumento = CtDocumentoPeer::retrieveByPK($request->getParameter('idDocumento'));

    $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $this->CtDocumento)));

    try
    {
      $this->CtDocumento->setFechaBaja(date('Y-m-d'));
      $this->CtDocumento->save();
      $this->getUser()->setFlash('notice', 'The item was deleted successfully.');
    }
    catch (PropelException $e)
    {
      $this->getUser()->setFlash('error', 'The item cannot be deleted.');
    }
    $this->setTemplate('delete');
    $this->setLayout('layout_iframe');

  }

  public function executeBatch(sfWebRequest $request)
  {
    $error = false;
    if (!$ids = $request->getParameter('ids'))
    {
      $this->getUser()->setFlash('error', 'You must at least select one item.');
      $error = true;
    }

    if (!($error) && (!$action = $request->getParameter('batch_action')))
    {
      $this->getUser()->setFlash('error', 'You must select an action to execute on the selected items.');

      $error = true;
    }

    if (!($error))
      try
      {
        // execute batch
        $this->executeBatchDelete($request);
      }
      catch (sfValidatorError $e)
      {
        $this->getUser()->setFlash('error', 'A problem occurs when deleting the selected items as some items do not exist anymore.');
      }

    $this->setTemplate('confirm');
    $this->setLayout('layout_iframe');

  }

  protected function executeBatchDelete(sfWebRequest $request)
  {
    $ids = $request->getParameter('ids');
    $ids = explode(',', $ids);
    $count = 0;
    foreach (CtDocumentoPeer::retrieveByPks($ids) as $object)
    {
      $object->setFechaBaja(date('Y-m-d'));
      $object->save();
      $count++;
    }

    if ($count >= count($ids))
    {
      $this->getUser()->setFlash('notice', 'The selected items have been deleted successfully.');
    }
    else
    {
      $this->getUser()->setFlash('error', 'A problem occurs when deleting the selected items.');
    }

  }

  public function executeUploadImage(sfWebRequest $request)
  {
    $id_documento = $request->getParameter('id');
    $this->CtDocumento = CtDocumentoPeer::retrieveByPK($id_documento);
    $this->form = new CtdocumentoFormUploadImage($this->CtDocumento);
    $this->getUser()->setAttribute('id_documento', $id_documento);
    $this->setLayout('layout_iframe');

  }

}
